package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.ClueJointRecheckEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.help.RecheckingAddRuleHelp;
import com.xbongbong.paas.model.ClueJointRecheckModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.RecheckRuleFromDbPojo;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.domain.entity.FormConfigEntity;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.recheck.pojo.RecheckAttrRulePojo;
import com.xbongbong.pro.recheck.pojo.RecheckFormRulePojo;
import com.xbongbong.pro.script.pojo.dto.AllScriptDTO;
import com.xbongbong.pro.script.pojo.vo.ScriptVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.RecheckingRuleEntity;
import com.xbongbong.saas.enums.FormConfigEnum;
import com.xbongbong.saas.enums.RecheckMatchWayEnum;
import com.xbongbong.saas.enums.RepeatTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.help.RecheckingRuleHelp;
import com.xbongbong.saas.model.FormConfigModel;
import com.xbongbong.saas.model.RecheckingRuleModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author jiangren.li
 * @version v1.0
 * @date 2022/11/9 15:15
 * @since v1.0
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/rechecking")
public class RecheckingScriptController {
    private static final Logger LOG = LoggerFactory.getLogger(RecheckingScriptController.class);
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private FormConfigModel formConfigModel;
    @Resource
    private ClueJointRecheckModel clueJointRecheckModel;
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private RecheckingRuleHelp recheckingRuleHelp;
    @Resource
    private RecheckingAddRuleHelp recheckingAddRuleHelp;
    @Resource
    private RecheckingRuleModel recheckingRuleModel;


    /**
     * 查重2.0需求
     * 同步查重相关配置到规则表
     * @author lijiangren
     * @date 2022-11-05 18 58
     */
    @RequestMapping(value = "/syncRecheckRule", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String syncRecheckRule(@RequestBody @Valid AllScriptDTO allScriptDTO, BindingResult br) {
        XbbResponse<ScriptVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                LOG.warn("开始同步查重配置");
                long currentTime = DateTimeUtil.getInt();
                //操作类型作为标识，0：灰度发布。1：代表全量发布
                Integer operate = allScriptDTO.getOperate();
                List<String> corpidList = new ArrayList<>();
                if (Objects.equals(BasicConstant.ZERO,operate)) {
                    corpidList = allScriptDTO.getCorpidList();
                } else {
                    corpidList = paasFormExplainModel.getCorpidList();
                }

                Integer pageSize = allScriptDTO.getPageSize();
                if (Objects.isNull(pageSize)) {
                    pageSize = 500;
                }
                int totalCount = corpidList.size();
                int pageNum = totalCount % pageSize > 0 ? totalCount / pageSize + 1 : totalCount / pageSize;
                for (int currentPage = 1; currentPage <= pageNum; currentPage++) {

                    int startIndex = (currentPage - 1) * pageSize;
                    int endIndex = currentPage * pageSize;
                    if (Objects.equals(currentPage, pageNum)) {
                        endIndex = totalCount;
                    }
                    LOG.warn("开始执行{}——{}家公司，进度{}/{}", startIndex, endIndex, currentPage, pageNum);

                    List<String> currentPageCorpidList = corpidList.subList(startIndex, endIndex);
                    Map<String, Object> param = new HashMap<>();
                    param.put("columns", "id,corpid,form_id,business_type,explains");
                    param.put("corpidIn", currentPageCorpidList);
                    param.put("del", DelEnum.NORMAL.getDel());
                    param.put("distributorMark", DistributorMarkEnum.OTHER.getCode());
                    param.put("businessTypeIn", Lists.newArrayList(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), XbbRefTypeEnum.CLUE.getCode(),XbbRefTypeEnum.CONTACT.getCode(),XbbRefTypeEnum.SALES_OPPORTUNITY.getCode()));
                    List<PaasFormExplainEntity> formExplainEntityList = paasFormExplainModel.findEntitys(param);
                    if (CollectionsUtil.isEmpty(formExplainEntityList)) {
                        continue;
                    }
                    try {
                        List<RecheckingRuleEntity> updateList = new ArrayList<>(formExplainEntityList.size());
                        List<Long> formIdIn = formExplainEntityList.stream().map(PaasFormExplainEntity::getFormId).collect(Collectors.toList());
                        //List<String> corpIdList = formExplainEntityList.stream().map(PaasFormExplainEntity::getCorpid).collect(Collectors.toList());
                        List<ClueJointRecheckEntity> clueJointRecheckEntityList = clueJointRecheckModel.getByFormIdListByScript(formIdIn, Lists.newArrayList(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), XbbRefTypeEnum.CONTACT.getCode()), currentPageCorpidList);
                        Map<String, Integer> corpidMap = new HashMap<>();
                        for (String s : currentPageCorpidList) {
                            Integer feeType = 0;
                            try {
                                feeType = packageHelp.getFeeType(s);
                                corpidMap.put(s,feeType);
                            } catch (Exception e) {

                            }
                        }

                        for (PaasFormExplainEntity entity : formExplainEntityList) {
                            String corpid = entity.getCorpid();
                            if (Objects.equals(corpid,BasicConstant.ZERO_STRING)) {
                                continue;
                            }
                            if (Objects.equals(BasicConstant.ONE,operate) && allScriptDTO.getCorpidList().contains(corpid)) {
                                continue;
                            }
                            Integer businessType = entity.getBusinessType();
                            Long formId = entity.getFormId();
                            if (StringUtil.isEmpty(entity.getExplains())) {
                                continue;
                            }
                            List<FieldAttrEntity> explainList = JSONArray.parseArray(entity.getExplains(), FieldAttrEntity.class);
                            explainList.removeIf(item -> (Objects.equals(item.getEditHide(), BasicConstant.ONE) || !Objects.equals(item.getIsOpen(), BasicConstant.ONE)));
                            Map<String, FieldAttrEntity> formExplainMap = ExplainUtil.getSubFormExplainMapByList(explainList);
                            if (formExplainMap.size() == 0) {
                                continue;
                            }

                            Integer feeType = corpidMap.get(corpid) !=null ? corpidMap.get(corpid) : 0;

                            //查重规则实体
                            RecheckingRuleEntity recheckingRuleEntity = new RecheckingRuleEntity();
                            recheckingRuleEntity.setCorpid(corpid);
                            recheckingRuleEntity.setBusinessType(businessType);
                            recheckingRuleEntity.setFormId(formId);
                            recheckingRuleEntity.setNormalEnable(BasicConstant.ONE);
                            ArrayList<RecheckFormRulePojo> checkToolRuleList = new ArrayList<>();
                            ArrayList<RecheckFormRulePojo> noRepeatRuleList = new ArrayList<>();
                            if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType)) {
                                //处理客户表单解析这部分规则
                                generateRecheckPojo(corpid, businessType, formId, formExplainMap, checkToolRuleList,noRepeatRuleList,feeType);

                            } else if (Objects.equals(XbbRefTypeEnum.CLUE.getCode(), businessType)) {
                                //处理线索表单解析这部分规则
                                generateRecheckPojo(corpid, businessType, formId, formExplainMap, checkToolRuleList,noRepeatRuleList,feeType);
                                //线索查询下该表单下的联合查重规则(查客户)
                                if (CollectionsUtil.isNotEmpty(clueJointRecheckEntityList)) {
                                    ClueJointRecheckEntity clueLinkCustomer = clueJointRecheckEntityList.stream().filter(body -> body.getCorpid().equals(corpid) && body.getFormId().equals(formId)
                                            && body.getLinkBusinessType().equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())).findAny().orElse(null);

                                    //ClueJointRecheckEntity clueLinkCustomer = clueJointRecheckModel.getByFormIdAndLinkBusinessType(formId, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), corpid);
                                    generateRecheckPojo2ClueJoin(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),checkToolRuleList, noRepeatRuleList,clueLinkCustomer);
                                    //线索查询下该表单下的联合查重规则(查客户)
                                    ClueJointRecheckEntity clueLinkContact = clueJointRecheckEntityList.stream().filter(body -> body.getCorpid().equals(corpid) && body.getFormId().equals(formId)
                                            && body.getLinkBusinessType().equals(XbbRefTypeEnum.CONTACT.getCode())).findAny().orElse(null);
                                    //ClueJointRecheckEntity clueLinkClue = clueJointRecheckModel.getByFormIdAndLinkBusinessType(formId, XbbRefTypeEnum.CONTACT.getCode(), corpid);
                                    generateRecheckPojo2ClueJoin(XbbRefTypeEnum.CONTACT.getCode(), checkToolRuleList, noRepeatRuleList, clueLinkContact);

                                }
                            } else if (Objects.equals(XbbRefTypeEnum.CONTACT.getCode(), businessType)) {
                                for (String attr : formExplainMap.keySet()) {
                                    FieldAttrEntity fieldAttrEntity = formExplainMap.get(attr);
                                    //联系人只有模板内判重
                                    if (Objects.equals(BasicConstant.ONE,fieldAttrEntity.getIsOpen()) && Objects.nonNull(fieldAttrEntity.getNoRepeat()) && Objects.equals(fieldAttrEntity.getNoRepeat(), BasicConstant.ONE)) {
                                        //该字段判重机会全部默认
                                        RecheckAttrRulePojo recheckRulePojo = new RecheckAttrRulePojo();
                                        //初始化对象默认模板内
                                        recheckRulePojo.setAttr(attr);
                                        recheckRulePojo.setLinkFormId(formId);
                                        recheckRulePojo.setLinkAttr(attr);
                                        recheckRulePojo.setLinkBusinessType(businessType);
                                        recheckRulePojo.setIsAll(BasicConstant.ZERO);
                                        recheckRulePojo.setMatchWay(RecheckMatchWayEnum.EXACT_MATCH.getCode());
                                        if (recheckingRuleHelp.checkNameAndPhone(attr)) {
                                            recheckRulePojo.setMatchWay(RecheckMatchWayEnum.FUZZY_MATCH.getCode());
                                        }
                                        RecheckFormRulePojo recheckFormRulePojo =new RecheckFormRulePojo();
                                        recheckFormRulePojo.setContact(Arrays.asList(recheckRulePojo));
                                        RecheckFormRulePojo noRepeatFormRulePojo =new RecheckFormRulePojo();
                                        BeanUtil.copyProperties(recheckFormRulePojo,noRepeatFormRulePojo);
                                        noRepeatFormRulePojo.setContact(Arrays.asList(recheckRulePojo));
                                        if (!recheckingRuleHelp.checkSerialNoAndUser(fieldAttrEntity.getFieldType())) {
                                            checkToolRuleList.add(recheckFormRulePojo);
                                        }
                                        noRepeatRuleList.add(noRepeatFormRulePojo);
                                    }
                                }
                            } else if (Objects.equals(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), businessType)) {
                                recheckingRuleEntity.setNormalEnable(BasicConstant.ZERO);
                                for (String attr : formExplainMap.keySet()) {
                                    FieldAttrEntity fieldAttrEntity = formExplainMap.get(attr);
                                    //机会只有模板内判重并且只同步新建不允许重复值
                                    if (Objects.equals(BasicConstant.ONE,fieldAttrEntity.getIsOpen()) && Objects.nonNull(fieldAttrEntity.getNoRepeat()) && Objects.equals(fieldAttrEntity.getNoRepeat(), BasicConstant.ONE)) {
                                        //该字段判重全部默认
                                        RecheckAttrRulePojo recheckRulePojo = new RecheckAttrRulePojo();
                                        //初始化对象默认模板内
                                        recheckRulePojo.setAttr(attr);
                                        recheckRulePojo.setLinkFormId(formId);
                                        recheckRulePojo.setLinkAttr(attr);
                                        recheckRulePojo.setLinkBusinessType(businessType);
                                        recheckRulePojo.setIsAll(BasicConstant.ZERO);
                                        recheckRulePojo.setMatchWay(RecheckMatchWayEnum.EXACT_MATCH.getCode());
                                        RecheckFormRulePojo noRepeatFormRulePojo =new RecheckFormRulePojo();
                                        noRepeatFormRulePojo.setOpportunity(Arrays.asList(recheckRulePojo));
                                        noRepeatRuleList.add(noRepeatFormRulePojo);
                                    }
                                }
                            }

                            recheckingRuleEntity.setCheckToolRule(JSON.toJSONString(checkToolRuleList));
                            recheckingRuleEntity.setNoRepeatRule(JSON.toJSONString(noRepeatRuleList));
                            updateList.add(recheckingRuleEntity);
                        }
                        if (CollectionsUtil.isNotEmpty(updateList)) {
                            recheckingRuleModel.insertBatchByScript(updateList);
                            //recheckingRuleModel.insertBatch(updateList);
                        }
                    } catch (Exception e) {
                        LOG.error("RecheckingScriptController.syncRecheckRule, fiall_corpidList:" + currentPageCorpidList, e);
                    }
                }
                long endTime = DateTimeUtil.getInt();
                LOG.warn("所有公司执行完毕，总耗时{}",(endTime - currentTime));
                response = new XbbResponse<>();
            } catch (XbbException e) {
                LOG.error("默认重复规则初始化失败",e);
                response = new XbbResponse<>();
            }
        }
        return JSON.toJSONString(response);
    }

    private void generateRecheckPojo2ClueJoin(Integer businessType, ArrayList<RecheckFormRulePojo> recheckFormRulePojos, ArrayList<RecheckFormRulePojo> noRepeatRuleList, ClueJointRecheckEntity clueLinkCustomer) {
        //不为空代表配置了联合查重规则
        if (Objects.nonNull(clueLinkCustomer)) {
            //判断客户是否开启   0代表没有开启，1代表开启
            if (Objects.equals(BasicConstant.ONE, clueLinkCustomer.getEnable())) {
                //联合客户查重处于 开启状态
                String rules = clueLinkCustomer.getRules();
                if (StringUtil.isNotEmpty(rules)) {
                    List<RecheckRuleFromDbPojo> recheckRuleFromDbPojoList = JSONArray.parseArray(rules,RecheckRuleFromDbPojo.class);
                    if (CollectionsUtil.isNotEmpty(recheckRuleFromDbPojoList)) {
                        for (RecheckRuleFromDbPojo recheckRuleFromDbPojo : recheckRuleFromDbPojoList) {
                            //recheckFormRulePojos封装的表单解析中查重不允许重复的字段
                            recheckFormRulePojos.forEach(item->{
                                List<RecheckAttrRulePojo> clueList = item.getClue();
                                if (CollectionsUtil.isNotEmpty(clueList)) {
                                    RecheckAttrRulePojo recheckAttrRulePojo = clueList.get(0);
                                    String recheckAttr = recheckAttrRulePojo.getAttr();
                                    if (Objects.nonNull(recheckAttr) && Objects.equals(recheckAttr,recheckRuleFromDbPojo.getAttr())) {
                                        RecheckAttrRulePojo recheckRulePojo = new RecheckAttrRulePojo();
                                        //初始化对象默认模板内
                                        Integer isAll = Objects.nonNull(recheckRuleFromDbPojo.getIsAll()) ? recheckRuleFromDbPojo.getIsAll():BasicConstant.ZERO;
                                        recheckRulePojo.setAttr(recheckRuleFromDbPojo.getAttr());
                                        Long linkFormId = Objects.equals(recheckRuleFromDbPojo.getIsAll(),BasicConstant.ZERO) ? recheckRuleFromDbPojo.getFormId():BasicConstant.ZERO;
                                        recheckRulePojo.setLinkFormId(linkFormId);
                                        recheckRulePojo.setLinkAttr(recheckRuleFromDbPojo.getLinkAttr());
                                        recheckRulePojo.setLinkBusinessType(clueLinkCustomer.getLinkBusinessType());
                                        recheckRulePojo.setIsAll(isAll);
                                        recheckRulePojo.setMatchWay(RecheckMatchWayEnum.EXACT_MATCH.getCode());
                                        if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),businessType)) {
                                            item.setCustomer(Arrays.asList(recheckRulePojo));
                                        } else {
                                            item.setContact(Arrays.asList(recheckRulePojo));
                                        }

                                    }
                                }
                            });

                            //noRepeatRuleList封装的表单解析中新建不允许重复的字段
                            noRepeatRuleList.forEach(item->{
                                List<RecheckAttrRulePojo> clueList = item.getClue();
                                if (CollectionsUtil.isNotEmpty(clueList)) {
                                    RecheckAttrRulePojo recheckAttrRulePojo = clueList.get(0);
                                    String recheckAttr = recheckAttrRulePojo.getAttr();
                                    if (Objects.nonNull(recheckAttr) && Objects.equals(recheckAttr,recheckRuleFromDbPojo.getAttr())) {
                                        RecheckAttrRulePojo recheckRulePojo = new RecheckAttrRulePojo();
                                        //初始化对象默认模板内
                                        Integer isAll = Objects.nonNull(recheckRuleFromDbPojo.getIsAll()) ? recheckRuleFromDbPojo.getIsAll():0;
                                        recheckRulePojo.setAttr(recheckRuleFromDbPojo.getAttr());
                                        Long linkFormId = Objects.equals(recheckRuleFromDbPojo.getIsAll(),BasicConstant.ZERO) ? recheckRuleFromDbPojo.getFormId():BasicConstant.ZERO;
                                        recheckRulePojo.setLinkFormId(linkFormId);
                                        recheckRulePojo.setLinkAttr(recheckRuleFromDbPojo.getLinkAttr());
                                        recheckRulePojo.setLinkBusinessType(clueLinkCustomer.getLinkBusinessType());
                                        recheckRulePojo.setIsAll(isAll);
                                        recheckRulePojo.setMatchWay(RecheckMatchWayEnum.EXACT_MATCH.getCode());
                                        if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),businessType)) {
                                            item.setCustomer(Arrays.asList(recheckRulePojo));
                                        } else {
                                            item.setContact(Arrays.asList(recheckRulePojo));
                                        }
                                    }
                                }
                            });
                        }
                    }
                }
            }
        }
    }

    /**
     * 封装查重规则实体，客户和线索 避免重复代码
     * @author lijiangren
     * @date 2022-11-09 14 10
     */
    private void generateRecheckPojo(String corpid, Integer businessType, Long formId, Map<String, FieldAttrEntity> fieldAttrEntityMap,List<RecheckFormRulePojo> checkToolRuleList,List<RecheckFormRulePojo> noRepeatRuleList,Integer feeType) throws XbbException {
        String nameRepeat = FormConfigEnum.CUSTOMER_NAME_REPEAT_TYPE.getConfig();
        String phoneRepeat = FormConfigEnum.CUSTOMER_PHONE_REPEAT_TYPE.getConfig();
        if (Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode())) {
            nameRepeat = FormConfigEnum.CLUE_NAME_REPEAT_TYPE.getConfig();
            phoneRepeat = FormConfigEnum.CLUE_PHONE_REPEAT_TYPE.getConfig();
        }

        for (String attr : fieldAttrEntityMap.keySet()) {
            FieldAttrEntity fieldAttrEntity = fieldAttrEntityMap.get(attr);
            List<RecheckAttrRulePojo> recheckRuleArrayList =new ArrayList<>();
            List<RecheckAttrRulePojo> noRepeatRuleArrayList =new ArrayList<>();
            if (Objects.equals(BasicConstant.ONE,fieldAttrEntity.getIsOpen())) {
                //查重工具
                RecheckAttrRulePojo recheckRulePojo = new RecheckAttrRulePojo();
                //初始化对象默认模板内
                recheckRulePojo.setAttr(attr);
                recheckRulePojo.setLinkFormId(formId);
                recheckRulePojo.setLinkAttr(attr);
                recheckRulePojo.setLinkBusinessType(businessType);
                recheckRulePojo.setIsAll(BasicConstant.ZERO);
                recheckRulePojo.setMatchWay(RecheckMatchWayEnum.EXACT_MATCH.getCode());
                //新建判重
                RecheckAttrRulePojo noRepeatRulePojo = new RecheckAttrRulePojo();
                BeanUtil.copyProperties(recheckRulePojo,noRepeatRulePojo);
                //判断查重参数是自定义还是系统字段
                if (Objects.equals(fieldAttrEntity.getIsRedundant(), BasicConstant.ONE)) {
                    if (Objects.nonNull(fieldAttrEntity.getNoRepeat()) && Objects.equals(fieldAttrEntity.getNoRepeat(), BasicConstant.ONE)) {
                        //判断是否是旗舰版，旗舰版自定义字段可以配置全局判重关联其他表单
                        if (Objects.equals(PackageTypeEnum.ULTIMATE.getType(), feeType)) {
                            //自定义字段
                            if (Objects.nonNull(fieldAttrEntity.getCustomRepeatType())) {
                                //判断是模板内还是全局判查
                                if (Objects.equals(fieldAttrEntity.getCustomRepeatType(), BasicConstant.ONE)) {
                                    //模板内
                                    if (!recheckingRuleHelp.checkSerialNoAndUser(fieldAttrEntity.getFieldType())) {
                                        recheckRuleArrayList.add(recheckRulePojo);
                                    }
                                    noRepeatRuleArrayList.add(noRepeatRulePojo);
                                } else if (Objects.equals(fieldAttrEntity.getCustomRepeatType(), BasicConstant.TWO)){
                                    //模板内判重 + 自定义全局判重
                                    //自定义全局判重，需要获取配置规则
                                    recheckRulePojo.setIsAll(BasicConstant.ONE);
                                    noRepeatRulePojo.setIsAll(BasicConstant.ONE);
                                    recheckRulePojo.setLinkFormId(BasicConstant.ZERO_LONG);
                                    noRepeatRulePojo.setLinkFormId(BasicConstant.ZERO_LONG);
                                    if (!recheckingRuleHelp.checkSerialNoAndUser(fieldAttrEntity.getFieldType())) {
                                        recheckRuleArrayList.add(recheckRulePojo);
                                    }
                                    noRepeatRuleArrayList.add(noRepeatRulePojo);
                                }
                            } else {
                                //模板内
                                if (!recheckingRuleHelp.checkSerialNoAndUser(fieldAttrEntity.getFieldType())) {
                                    recheckRuleArrayList.add(recheckRulePojo);
                                }
                                noRepeatRuleArrayList.add(noRepeatRulePojo);
                            }
                        } else {
                            //该字段模板内判重
                            if (!recheckingRuleHelp.checkSerialNoAndUser(fieldAttrEntity.getFieldType())) {
                                recheckRuleArrayList.add(recheckRulePojo);
                            }
                            noRepeatRuleArrayList.add(noRepeatRulePojo);
                        }
                    }
                } else {
                    //特殊处理名称、电话字段
                    if (recheckingRuleHelp.checkNameAndPhone(attr)) {
                        FormConfigEntity formConfigEntity = null;
                        if (Objects.equals(attr, StringConstant.NAME)) {
                            formConfigEntity = formConfigModel.getEntityByFormId(corpid, formId, nameRepeat);
                        } else {
                            formConfigEntity = formConfigModel.getEntityByFormId(corpid, formId, phoneRepeat);
                        }

                        recheckRulePojo.setMatchWay(RecheckMatchWayEnum.FUZZY_MATCH.getCode());
                        noRepeatRulePojo.setMatchWay(RecheckMatchWayEnum.EXACT_MATCH.getCode());
                        if (formConfigEntity != null) {
                            // 客户名称、电话没有维护noRepeat到表单解析，所以需要查配置来判断是否存在。
                            if (Objects.equals(formConfigEntity.getConfigValue(), RepeatTypeEnum.REPEAT_SINGLE.getType().toString())) {
                                //模板内判重(模糊)
                                recheckRuleArrayList.add(recheckRulePojo);
                                noRepeatRuleArrayList.add(noRepeatRulePojo);
                            } else if (Objects.equals(formConfigEntity.getConfigValue(), RepeatTypeEnum.REPEAT_ALL.getType().toString())) {
                                //全局判重
                                recheckRulePojo.setIsAll(BasicConstant.ONE);
                                noRepeatRulePojo.setIsAll(BasicConstant.ONE);
                                recheckRulePojo.setLinkFormId(BasicConstant.ZERO_LONG);
                                noRepeatRulePojo.setLinkFormId(BasicConstant.ZERO_LONG);
                                recheckRuleArrayList.add(recheckRulePojo);
                                noRepeatRuleArrayList.add(noRepeatRulePojo);
                            } else {
                                //不判重
                            }

                        } else {
                            //通过表单解析本身noRepeat判重
                            if (Objects.equals(fieldAttrEntity.getNoRepeat(), BasicConstant.ONE)) {
                                //模板内判重
                                recheckRuleArrayList.add(recheckRulePojo);
                                noRepeatRuleArrayList.add(noRepeatRulePojo);
                            } else {
                                //不判重
                            }
                        }
                    } else {
                        //其他系统字段比如流水号、成员单选模板内判重
                        if (Objects.equals(fieldAttrEntity.getNoRepeat(), BasicConstant.ONE)) {
                            //模板内判重
                            recheckRuleArrayList.add(recheckRulePojo);
                            if (!recheckingRuleHelp.checkSerialNoAndUser(fieldAttrEntity.getFieldType())) {
                                noRepeatRuleArrayList.add(noRepeatRulePojo);
                            }
                        }
                    }
                }
            }

            RecheckFormRulePojo recheckFormRulePojo = new RecheckFormRulePojo();
            RecheckFormRulePojo noRepeartFormRulePojo = new RecheckFormRulePojo();
            if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),businessType)) {
                if (CollectionsUtil.isNotEmpty(recheckRuleArrayList)) {
                    recheckFormRulePojo.setCustomer(recheckRuleArrayList);
                    checkToolRuleList.add(recheckFormRulePojo);
                }
                if (CollectionsUtil.isNotEmpty(noRepeatRuleArrayList)) {
                    noRepeartFormRulePojo.setCustomer(noRepeatRuleArrayList);
                    noRepeatRuleList.add(noRepeartFormRulePojo);
                }
            } else if (Objects.equals(XbbRefTypeEnum.CLUE.getCode(),businessType)) {
                if (CollectionsUtil.isNotEmpty(recheckRuleArrayList)) {
                    recheckFormRulePojo.setClue(recheckRuleArrayList);
                    checkToolRuleList.add(recheckFormRulePojo);
                }
                if (CollectionsUtil.isNotEmpty(noRepeatRuleArrayList)) {
                    noRepeartFormRulePojo.setClue(noRepeatRuleArrayList);
                    noRepeatRuleList.add(noRepeartFormRulePojo);
                }
            }
        }
    }

    /**
     * @description 初始化默认查重规则
     * @author yanglei
     * @date 2022/11/9 12:08
     * @param allScriptDTO
     * @param br
     * @return String
     */
    @RequestMapping(value = "/initDefaultRecheckRule", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String initDefaultRecheckRule(@RequestBody @Valid AllScriptDTO allScriptDTO, BindingResult br) throws XbbException {
        XbbResponse<String> response;
        if ( br.hasErrors() ) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            if (!proBaseConfig.getXbbCode().equals(allScriptDTO.getXbbCode())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
            }
            //需要初始化默认重复规则的业务
            List<Integer> initBusinessTypeList = Arrays.asList(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),
                    XbbRefTypeEnum.CONTACT.getCode(),XbbRefTypeEnum.CLUE.getCode(),XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
            try{
                List<RecheckingRuleEntity> list = new ArrayList<>();
                for(Integer businessType : initBusinessTypeList){
                    String redisKey = StringConstant.DEFAULT_CORPID + "_" + businessType;
                    RecheckingRuleEntity entity = recheckingAddRuleHelp.initDefaultRecheckRuleEntity(businessType);
                    list.add(entity);
                    JSONObject jsonObject = new JSONObject();
                    JSONArray checkToolArr = JSON.parseArray(entity.getCheckToolRule());
                    JSONArray noRepeatArr = JSON.parseArray(entity.getNoRepeatRule());
                    jsonObject.put(StringConstant.CHECK_TOOL_RULE,checkToolArr);
                    jsonObject.put(StringConstant.NO_REPEAT_RULE,noRepeatArr);
                    jsonObject.put(StringConstant.NORMAL_ENABLE,entity.getNormalEnable());
                    paasRedisHelper.setValue(RedisPrefixConstant.DEFAULT_RECHECKING_RULE, redisKey, jsonObject, TimeConstant.SECONDS_PER_DAY);
                }
                recheckingRuleModel.insertBatch(list);
                response = new XbbResponse<>("success");
            }catch (Exception e){
                LOG.error("默认重复规则初始化失败",e);
                response = new XbbResponse<>("faild");
            }
        }
        return JSON.toJSONString(response);
    }

}
